import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";

const FUTURES_BASE = "/seller/verify/inquiry";

export interface FuturesListItem {
  id: number;
  verify_code: string;
  status: number;
  buyer_amount: number;
  seller_amount: number;
  buyer_remark?: string;
  buyer_expected_date?: string | null;
  buyer_verify_create?: string | null;
  seller_verify_create?: string | null;
  product?: Record<string, any>;
  [key: string]: any;
}

export interface FuturesDetail {
  buyer_amount: number;
  verify_code: string;
  buyer_remark: string;
  seller_remark: string;
  seller_remark_media: {
    img: string[];
    video: string[];
  };
  seller_amount: number;
  seller_confirm_price: number;
  seller_delivery_date: string;
  buyer_expected_price: number;
  buyer_expected_date: string;
  product: Record<string, any>;
}

export interface FuturesListResponse {
  list: Array<FuturesListItem>;
  pagination: {
    total: number;
    page: number;
    page_size: number;
    current_page?: number;
    currentPage?: number;
    pageSize?: number;
  };
}

export type FuturesListResult = ApiResponse<FuturesListResponse>;
export type FuturesDetailResult = ApiResponse<FuturesDetail>;

const mergeMediaPayload = (media: any) => {
  if (!media) return undefined;
  if (typeof media !== "object") return media;
  const images = Array.isArray(media.img) ? media.img : [];
  const videos = Array.isArray(media.video) ? media.video : [];
  return {
    img: images,
    video: videos
  };
};

const futuresApi = {
  fetch(params: Record<string, any>) {
    return http.request<FuturesListResult>("get", FUTURES_BASE, {
      params
    });
  },

  read(id: number | string) {
    return http.request<FuturesDetailResult>("get", `${FUTURES_BASE}/${id}`);
  },

  update(id: number | string, payload: Record<string, any>) {
    const data = {
      ...payload,
      seller_remark_media: mergeMediaPayload(payload.seller_remark_media)
    };

    return http.request<ApiResponse<FuturesDetail>>(
      "put",
      `${FUTURES_BASE}/${id}`,
      {
        data
      }
    );
  }
};

export default futuresApi;
